is cached
ErrorsCollection

is cached

Synthesised documentation from type/Routine

From type/Routine

See Original text in context

multi sub trait_mod:<is>(Routine $r:$cached!)

Causes the return value of a routine to be stored, so that when subsequent calls with the same list of arguments are made, the stored value can be returned immediately instead of re-running the routine.[1]

Useful when storing and returning the computed value is much faster than re-computing it every time, and when the time saved trumps the cost of the use of more memory.

Even if the arguments passed to the routine are "reference types" (such as objects or arrays), then for the purpose of caching they will only be compared based on their contents. Thus the second invocation will hit the cache in this case:

say foo( [123] );   # runs foo 
say foo( [123] );   # doesn't run foo, uses cached value 

Since it's still at the experimental stage, you will have to insert the use experimental :cached; statement in any module or script that uses it.

use experimental :cached;
 
sub nth-prime(Int:D $x where * > 0is cached {
    say "Calculating {$x}th prime";
    return (2..*).grep(*.is-prime)[$x - 1];
}
 
say nth-prime(43);
say nth-prime(43);
say nth-prime(43);

produces this output:

Calculating 43th prime
191
191
191

Marks something as deprecated